<?php
declare (strict_types=1);

namespace app\common\middleware;

/**
 * 跨域请求
 * Class Cross
 * @package app\middleware
 */
class Cross
{
    /**
     * 处理跨域请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */

    public function handle($request, \Closure $next)
    {
        header('Access-Control-Allow-Origin: ' . $request->server('HTTP_ORIGIN'));
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, admin-token, sessionId");
        if (strtoupper($request->method()) == "OPTIONS") {
            $ret_json = json([
                'code' => 0,
                'msg' => 'success',
                'data' => ['CrossMiddleware' => 'success'
                ]]);
            return $ret_json;
        }
        return $next($request);

    }
}
